package com.imstlife.vending.api;

import android.os.Build;
import android.util.Log;

import com.imstlife.vending.activity.MyApplication;
import com.imstlife.vending.net.RetrofitManager;
import com.imstlife.vending.net.RetrofitServer;
import com.imstlife.vending.net.SimpleObserver;
import com.imstlife.vending.utils.AppUtil;
import com.imstlife.vending.utils.Cof;
import com.imstlife.vending.utils.GsonUtil;
import com.imstlife.vending.utils.HttpUtil;
import com.imstlife.vending.vo.CheckOutRespone;
import com.imstlife.vending.vo.CheckUpdateRespone;
import com.imstlife.vending.vo.DeviceLoginResponse;
import com.imstlife.vending.vo.GetDrinkListResponse;
import com.imstlife.vending.vo.SyncOutTradeResponse;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 李海锋 on 2017/3/23.
 */

public class MarvAPI {

    private String TAG = "MarvAPI";

    private static MarvAPI ins;

    public static MarvAPI getInstance(){
        return  ins==null?ins = new MarvAPI():ins;
    }

    public static String getDeviceType() {
        if (Build.MODEL.contains("3188")) {
            return "RK3188";
        } else if (Build.MODEL.contains("3288")) {
            return "RK3288";
        } else if (Build.MODEL.contains("marvsmart")) {
            return "RK3128";
        } else if (Build.MODEL.contains("Allwinner")) {
            return "Allwinner";
        } else {
            return "UnKnow";
        }
    }
    /**
     * 设备改了登录
     */
    public void deviceLogin(final String url,String size,  final String deviceId,final String versionName,final int versionCode, final APIListener listener){

        if (HttpUtil.isNetworkAvailable(MyApplication.getInstance())) {
            Log.i(TAG,"设备登陆调用");
            RequestParams p = new RequestParams();
            p.put("deviceId",deviceId);
            p.put("deviceType","vending");
            p.put("versionCode",versionCode);
            p.put("versionName",versionName);
            p.put("screenSize",size);
            p.put("systemVersion",android.os.Build.DISPLAY);
            p.put("chipVersion",getDeviceType());
            HttpUtil.post(Cof.Interface.URL_DEVICE_LOGIN, p,
                    new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(String content) {
                            Log.i(TAG,"设备登陆返回："+ content);
                            try {
                                DeviceLoginResponse response = GsonUtil.deserialize(content,DeviceLoginResponse.class);
                                listener.onSuccess(response);
                            }catch (Exception e){
                                e.printStackTrace();
                                Log.i(TAG,"登陆数据解析失败");
                                listener.onFailure("登陆数据解析失败");
                            }
                        }
                        @Override
                        public void onFailure(Throwable error) {
                            super.onFailure(error);
                            Log.i(TAG,"设备登陆失败");
                           listener.onFailure("登陆失败");
                        }
                    });
        } else {
            Log.i(TAG,"设备登陆网络异常");
            listener.onNetError("登陆网络异常");
        }
    }

    /**
     * 加载商品列表
     */
    public void getDrinkList(String url, String deviceId, final APIListener listener) {

        if (HttpUtil.isNetworkAvailable(MyApplication.getInstance())) {

            RetrofitManager.createJsonService(RetrofitServer.class)
                    .getDrinkList(url,deviceId)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new SimpleObserver<String>() {
                        @Override
                        public void onNext(@NonNull String s) {
                            Log.i(TAG,"获取商品里列表返回："+ s);
                            try {
                                GetDrinkListResponse response = GsonUtil.deserialize(s,GetDrinkListResponse.class);

                                listener.onSuccess(response);
                            } catch (Exception e) {
                                listener.onFailure("获取商品列表失败1="+e.toString());
                                Log.i(TAG,"获取商品列表失败");
                            }

                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            Log.i(TAG,"获取商品列表失败");
                            listener.onFailure("获取商品列表失败2="+e.toString());
                        }
                    });

//            RequestParams p = new RequestParams();
//            p.put("deviceId",deviceId);
//            HttpUtil.post(url, p,
//                    new AsyncHttpResponseHandler() {
//                        @Override
//                        public void onSuccess(String content) {
//                            Log.i(TAG,"获取商品里列表返回："+ content);
//                            try {
//                                GetDrinkListResponse response = GsonUtil.deserialize(content,GetDrinkListResponse.class);
//
//                                listener.onSuccess(response);
//                            } catch (Exception e) {
//                                listener.onFailure("获取商品列表失败");
//                                Log.i(TAG,"获取商品列表失败");
//                            }
//                        }
//                        @Override
//                        @Deprecated
//                        public void onFailure(Throwable error) {
//                            Log.i(TAG,"获取商品列表失败");
//                           listener.onFailure("获取商品列表失败");
//                        }
//                    });
        } else {
            Log.i(TAG,"获取商品列表网络异常");
            listener.onNetError("获取商品列表网络异常");
        }

    }

    /**
     * 检查更新
     * @param url  接口地址
     * @param deviceId  设备号
     * @param key  应用key
     * @param versionName  版本1名
     * @param versionCode 版本号
     * @param listener 回调
     */
    public void checkUpdate(String url, String deviceId,String key,String versionName,String versionCode, final APIListener listener) {

        if (HttpUtil.isNetworkAvailable(MyApplication.getInstance())) {
            RequestParams p = new RequestParams();
            p.put("deviceId",deviceId);
            p.put("key",Cof.KEY);
            p.put("versionCode", AppUtil.getVersionCode(MyApplication.getInstance()) + "");
            p.put("versionName", AppUtil.getVersionName(MyApplication.getInstance()));
            HttpUtil.post(url, p,
                    new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(String content) {
                            Log.i(TAG,"检查更新返回："+ content);
                            try {
                                CheckUpdateRespone response = GsonUtil.deserialize(content,CheckUpdateRespone.class);
                                listener.onSuccess(response);
                            } catch (Exception e) {
                                listener.onFailure("检查更新失败");
                                Log.i(TAG,"检查更新失败");
                            }
                        }
                        @Override
                        @Deprecated
                        public void onFailure(Throwable error) {
                            Log.i(TAG,"检查更新失败");
                            listener.onFailure("检查更新失败");
                        }
                    });
        } else {
            Log.i(TAG,"检查更新网络异常");
            listener.onNetError("检查更新网络异常");
        }

    }

    /**
     *
     * @param url 接口地址
     * @param deviceId 设备号
     * @param outTradeNo 订单号
     * @param state 状态
     * @param listener 监听
     */
    public void syncOutTrade(String url, String deviceId, String outTradeNo, int state, final APIListener listener){
        if(HttpUtil.isNetworkAvailable(MyApplication.getInstance())){

            RetrofitManager.createJsonService(RetrofitServer.class)
                    .sync(url,deviceId,outTradeNo,state+"")
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribeOn(Schedulers.io())
                    .subscribe(new SimpleObserver<String>() {
                        @Override
                        public void onNext(@NonNull String s) {
                            Log.i(TAG,"订单同步返回："+ s);
                            try {
                                SyncOutTradeResponse response = GsonUtil.deserialize(s,SyncOutTradeResponse.class);
                                listener.onSuccess(response);
                            } catch (Exception e) {
                                listener.onFailure("订单同步失败");
                                Log.i(TAG,"订单同步失败");
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            Log.i(TAG,"订单同步失败");
                            listener.onFailure("订单同步失败");
                        }
                    });


//            RequestParams params = new RequestParams();
//            params.put("deviceId",deviceId);
//            params.put("outTradeNo",outTradeNo);
//            params.put("state",state+"");
//            HttpUtil.post(url,params,new AsyncHttpResponseHandler(){
//                @Override
//                public void onSuccess(String content) {
//                    super.onSuccess(content);
//                    Log.i(TAG,"订单同步返回："+ content);
//                    try {
//                        SyncOutTradeResponse response = GsonUtil.deserialize(content,SyncOutTradeResponse.class);
//                        listener.onSuccess(response);
//                    } catch (Exception e) {
//                        listener.onFailure("订单同步失败");
//                        Log.i(TAG,"订单同步失败");
//                    }
//                }
//
//                @Override
//                public void onFailure(Throwable error) {
//                    super.onFailure(error);
//                    Log.i(TAG,"订单同步失败");
//                    listener.onFailure("订单同步失败");
//
//                }
//            });



        }else{
            Log.i(TAG,"订单同步网络异常");
            listener.onNetError("检查更新网络异常");
        }


    }

    /**
     *
     * @param url 接口地址
     * @param deviceId 设备号
     * @param listener 监听
     */
    public void checkOutState(String url, String deviceId,  final APIListener listener){
        if(HttpUtil.isNetworkAvailable(MyApplication.getInstance())){
            RequestParams params = new RequestParams();
            params.put("deviceId",deviceId);

            HttpUtil.post(url,params,new AsyncHttpResponseHandler(){
                @Override
                public void onSuccess(String content) {
                    super.onSuccess(content);
                    Log.i(TAG,"检查出货："+ content);
                    try {
                        CheckOutRespone response = GsonUtil.deserialize(content,CheckOutRespone.class);
                        listener.onSuccess(response);
                    } catch (Exception e) {
                        listener.onFailure("检查出货失败");
                        Log.i(TAG,"检查出货失败");

                    }
                }

                @Override
                public void onFailure(Throwable error) {
                    super.onFailure(error);
                    Log.i(TAG,"检查出货失败");
                    listener.onFailure("检查出货失败");

                }
            });



        }else{
            Log.i(TAG,"检查出货网络异常");
            listener.onNetError("检查出货网络异常");
        }


    }


    public interface APIListener{

        void onSuccess(Object data);

        void onFailure(String msg);

        void onNetError(String msg);

    }

}
